package com.lkx.controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.lkx.cache.SeckillRedisCache;
import com.lkx.limit.Limit;
import com.lkx.service.OrderService;
import com.lkx.utils.PageUtils;
import com.lkx.utils.R;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.lkx.domain.SeckillDO;
import com.lkx.service.SeckillService;

/**
 * 
 * 
 * @author likaixuan
 * @email 934268568@qq.com
 * @date 2018-08-30 14:58:39
 */

@RestController
@RequestMapping("/seckill")
public class SeckillController {

	private final static Logger logger = LoggerFactory.getLogger(SeckillController.class);


    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

	private static int corePoolSize = Runtime.getRuntime().availableProcessors();
	//创建线程池  调整队列数 拒绝服务
	private static ThreadPoolExecutor executor  = new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10l, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>(1000));

	@Autowired
	private SeckillService seckillService;
	@Autowired
	private OrderService orderService;
	@Autowired
    private SeckillRedisCache seckillRedisCache;


	@ApiOperation(value="秒杀一(最low实现)",nickname="")
    @PostMapping("/start")
    public R Seckill(Long seckillId){
        logger.info("开始秒杀一(会出现超卖)");
        seckillService.resetNum(100,seckillId);
        orderService.remove(seckillId);
        for(int i=0;i<1000;i++){
            final long userId = i;
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    R result = seckillService.startSeckill(seckillId, userId);
                    if(result!=null){
                        logger.info("用户:{}{}",userId,result.get("msg"));
                    }else{
                        logger.info("用户:{}{}",userId,"哎呦喂，人也太多了，请稍后！");
                    }
                }
            };
            executor.execute(task);
        }

        try {
            Thread.sleep(10000);
            int  seckillCount = seckillService.getSeckillOrderCount(seckillId);
            logger.info("一共秒杀出{}件商品",seckillCount);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    @ApiOperation(value="秒杀2",nickname="")
    @PostMapping("/startSeckillRedis")
    public R seckillRedis(Long seckillId){
        logger.info("开始秒杀2");
        seckillService.resetNum(100,seckillId);
        orderService.remove(seckillId);
        seckillRedisCache.setSeckillCount(seckillId,100,300L);
        for(int i=0;i<1000;i++){
            final long userId = i;
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    R result = seckillService.startSeckillRedis(seckillId, userId);
                    if(result!=null){
                        logger.info("用户:{}{}",userId,result.get("msg"));
                    }else{
                        logger.info("用户:{}{}",userId,"哎呦喂，人也太多了，请稍后！");
                    }
                }
            };
            executor.execute(task);
        }

        try {
            Thread.sleep(10000);
            int  seckillCount = seckillService.getSeckillOrderCount(seckillId);
            logger.info("一共秒杀出{}件商品",seckillCount);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    @Limit(key = "test", period = 10, count = 2, name="resource", prefix = "limit")
	@PostMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		List<SeckillDO> seckillList = seckillService.list(params);
		int total = seckillService.count(params);
		PageUtils pageUtils = new PageUtils(seckillList, total);
		return pageUtils;
	}

	
	/**
	 * 保存
	 */
	@PostMapping("/save")
	public R save(SeckillDO seckill){
		if(seckillService.save(seckill)>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	public R remove( Long id){
		if(seckillService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		seckillService.batchRemove(ids);
		return R.ok();
	}
	
}
